
import { getCuesIndustry } from "../../../../service/api/api-cues-industry";
import { getCuesTopicDetails, initSaveTopicTreeAssignOrganization, initSaveTopicTreeLinkageOrganization, saveCuesTopic, selectCuesTopicManage, sendCuesTopicSendTemplateMessage, updateTopicManageRecordState } from "../../../../service/api/api-cues-topic";
import Message from 'tdesign-miniprogram/message/index';
import Toast from 'tdesign-miniprogram/toast/index';
// pages/cues/topic/create/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUser: {},//当前用户
    access: {} as any,// 当前用户权限
    mode: 0,//当前选题类型

    //初始化数据
    initSaveTreeAssignOrganizations: [],//初始化保存树形 指派 组织列表
    initSaveTreeLinkageOrganizations: [],//初始化保存树形 协助 组织列表
    //组件控制对象
    viewDrawerIndustryVisible: false,//行业抽屉是否打开
    viewDrawerAssignVisible: false,//选择指派征集单位的选择器是否打开
    viewDrawerLinkageVisible: false,//选择协作媒体的选择器是否打开
    viewShowSubmitVisible: false,//是否确认提交
    //展示数据
    showIndustryName: '',//选择的行业名称
    showIndustryList: [],//行业列表
    showOrganizations: '',//展示选中的指派征集单位
    showLinkageOrganizations: '',//展示选中的协作媒体

    //加载判断字段
    isLoadAssignOrganizations: true,//指派征集单位是否在加载中
    isLoadLinkageOrganizations: true,//协作媒体是否在加载中

    //表单对象
    name: '',//标题
    grade: '',//分类
    showGrade: false,//是否显示分类
    selectedIndustryIds: [],//选中的行业id
    labelsList: [],//标签列表
    labelName: '',//标签名称
    showLabelList: [],//标签是否显示
    planContent: '',//计划描述文本
    datetimeVisible: false,//时间选择器是否显示
    datetime: new Date().getTime(),//选择的时间
    // nowTime: new Date().getTime(),//当前时间
    datetimeText: '',//所选择的时间
    assignOrganizationIds: [],//所选指派征集单位
    linkageOrganizationIds: [],//所选指派征集单位
    helpContent: '',//协助描述文本
    recordDescribes: '',//申报描述文本
    showConfirm: false,//是否显示是否推送全局的提示框
    topicId: '',//这个选题的id
    saveTopicId: '',//如果是修改的话这个被修改的选题的id
    topicDetails: {},//该选题的详情
    isSaveLinkageOrganization: {},//是否是编辑选题协助媒体
    isSaveLinkageOrganizationNodes: [],//是编辑选题所勾选的协助媒体
    isSaveAssignOrganization: false,//是否是编辑选题征集单位
    isSaveAssignOrganizationNodes: [],//是编辑选题所勾选的征集单位
    treeLinkageOrganizationIds: [],//选中的协作媒体
    treeAssignOrganizationIds: [],//选中的指派征集单位
  },

  //获取修改选题详情时已选中的协助媒体
  async getTreeLinkageOrganizationList(list) {
    const selectNode = list.map((item) => item.name)
    this.setData({
      isSaveLinkageOrganization: true,
      isSaveLinkageOrganizationNodes: selectNode,
    })
  },
  //获取修改选题详情时已选中的指派征集单位
  async getTreeAssignOrganizationList(list) {
    const selectNode = list.map((item) => item.name)
    this.setData({
      isSaveAssignOrganization: true,
      isSaveAssignOrganizationNodes: selectNode,
    })
  },
  //获取该选题的详情
  async getTopicDetails(id) {
    try {
      const response = await selectCuesTopicManage({ id });
      if (response.code === 0) {
        let topicDetails = response.data
        topicDetails.labelNames.map((item) => {
          this.data.showLabelList.push(true)
        })
        let selectOrganizations = topicDetails.assignOrganizations.map((item) => item.name).join('/')
        if (selectOrganizations.length > 10 && selectOrganizations.length !== 0) {
          selectOrganizations = selectOrganizations.slice(0, 10) + "..."
        }
        let selectOrganizationIds = topicDetails.assignOrganizations.map((item) => item.id)
        this.getTreeAssignOrganizationList(topicDetails.assignOrganizations)

        let selectTreeLinkageOrganizationIds = new Array()
        let selectTreeLinkageOrganizations = "";
        if (topicDetails.isLinkage === 1) {
          selectTreeLinkageOrganizations = topicDetails.linkageOrganizations.map((item) => item.name).join('/')
          if (selectTreeLinkageOrganizations.length > 10 && selectTreeLinkageOrganizations.length !== 0) {
            selectTreeLinkageOrganizations = selectTreeLinkageOrganizations.slice(0, 10) + "..."
          }
          selectTreeLinkageOrganizationIds = topicDetails.linkageOrganizations.map((item) => item.id)
          this.getTreeLinkageOrganizationList(topicDetails.linkageOrganizations)
        }

        this.setData({
          topicDetails,
          grade: topicDetails.grade,
          name: topicDetails.name,
          showIndustryName: topicDetails.industryNames,
          labelsList: topicDetails.labelNames,
          planContent: topicDetails.content,
          datetime: topicDetails.deadlineTime,
          helpContent: topicDetails.linkageDescribes,
          showLabelList: this.data.showLabelList,
          selectedIndustryIds: topicDetails.industryIds,
          datetimeText: topicDetails.deadlineTime,
          showOrganizations: selectOrganizations,
          showLinkageOrganizations: selectTreeLinkageOrganizations,
          treeAssignOrganizationIds: selectOrganizationIds,
          treeLinkageOrganizationIds: selectTreeLinkageOrganizationIds,
        })
      }
    } catch (error) { }
  },
  //选择重要程度（分类）
  handleChangeGrade(e) {
    this.setData({
      grade: e.detail.value,
    });
  },
  //输入标题
  onInputName(e) {
    this.setData({
      name: e.detail.value
    })
  },
  //显示是否确认提交
  showSubmitDialog() {
    this.setData({ viewShowSubmitVisible: true });
  },
  //隐藏是否确认提交
  closeSubmitDialog() {
    this.setData({ viewShowSubmitVisible: false });
  },
  //加载行业列表
  async loadCuesIndustryData() {
    try {
      const response = await getCuesIndustry();
      this.setData({
        showIndustryList: response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      })
    } catch (error) { }
  },
  //输入标签
  onLabelNameInput(e) {
    const re = new RegExp('^[\u4E00-\u9FA5A-Za-z0-9]+$');
    for (const elem of e.detail.value) {
      if (re.test(elem)) {
      } else {
        Message.warning({
          context: this,
          offset: [20, 32],
          duration: 5000,
          content: '只能输入汉字、英文字母和数字',
        });
        return;
      }
    }
    this.setData({
      labelName: e.detail.value
    })
  },
  handleAddLabels() {
    const { labelName, labelsList } = this.data;
    if (labelName && labelsList.indexOf(labelName) === -1) {
      this.data.labelsList.push(labelName);
      this.data.showLabelList.push(true);
      this.setData({
        labelName: '',
        labelsList: this.data.labelsList,
        showLabelList: this.data.showLabelList
      });
    } else {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '标签已存在',
      });
    }
  },
  //删除标签
  handleTagClose(e) {
    const index = e.currentTarget.dataset.index
    this.data.labelsList.splice(index, 1); // 删除索引为index的标签
    this.data.showLabelList.splice(index, 1); // 删除对应的show数组元素
    this.setData({
      labelsList: this.data.labelsList,
      showLabelList: this.data.showLabelList
    })
  },
  //输入计划描述
  onPlanContentInput(e) {
    this.setData({
      planContent: e.detail.value
    })
  },
  //显示时间选择器
  showPicker(e) {
    this.setData({
      datetimeVisible: true,
    });
  },
  //隐藏时间选择器
  hidePicker() {
    this.setData({
      datetimeVisible: false,
    });
  },
  //确认所选择的时间
  onConfirm(e) {
    const { value } = e.detail;
    if (!this.onComfirmSelectTime(value)) {
    } else {
      this.setData({
        datetime: value,
        datetimeText: value,
      });
      this.hidePicker();
    }
  },
  //限定选择的截止时间只能是当天之后
  onColumnChange(event) {
    const { value } = event.detail;
    this.onComfirmSelectTime(value)
  },
  //判断选择的截止时间是否在当天之前
  onComfirmSelectTime(value) {
    const selectedTime = new Date(value).getTime();
    const currentTime = new Date().getTime();
    if (selectedTime < currentTime) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择当前时间之后的时间',
      });
      return false; // 阻止选择
    } else {
      return true;
    }
  },
  /**
   * 初始化 指定单位 和 协作 单位
   * ===========================================================================================================================================================
   */
  /**
   * 预备Tree结构数据
   * @param data
   */
  readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = [];
    if (data) {
      data.forEach((val) => {
        if (val.isFolder === 1 && val.children === undefined) {
        } else {
          treeData.push({
            name: val.name,
            id: val.id,
            parentId: val.parentId,
            checkbox: 0,
            isFolder: val.isFolder,
            isChildren: val.children === undefined ? 0 : 1,
            children: this.readyTreeData(val.children as AdminOrganizationData.Organization[]),
          });
        }
      });
    }
    return treeData;
  },
  /**
  * 预备Tree结构数据
  * @param data
  */
  readyTreeData2(dataTree: [], selectIds: []): any {
    if (dataTree.length > 0) {
      let list = dataTree.map(item => {
        if (item.isChildren == 1) {
          item.children = this.readyTreeData2(item.children, selectIds);
          let noChildren = item.children.filter((item) => item.checked === 0); //过滤出未选中的
          let noLength = noChildren.length;
          if (noLength == 0) { //未选中的 == 0 ，选中状态
            let pingChildren = item.children.filter((item) => item.checked === -1); //过滤出平的，未全选中
            let pingLength = pingChildren.length;
            if (pingLength == 0) {//平的 == 0，选中状态
              item.checked = 1;
            } else {//平的 != 0, 平状态 
              item.checked = -1;
            }
          } else if (noLength == item.children.length) { //未选中的 == 孩子长度，表示 父节点 未选中
            item.checked = 0;
          } else { //未选中的 >0 && < 孩子长度，表示 父节点 平的
            item.checked = -1;
          }
        } else {
          item.checked = selectIds.includes(item.id) ? 1 : 0
        }
        return item
      })
      return list;
    }
    return []
  },
  /**
  * 加载 初始化 指派征集 单位
  */
  async loadInitSaveTopicTreeAssignOrganization() {
    try {
      const response = await initSaveTopicTreeAssignOrganization();
      if (response.code === 0) {
        this.setData({
          initSaveTreeAssignOrganizations: this.readyTreeData(response.data),
          isLoadAssignOrganizations: false
        })
      }
    } catch (error) { }
  },
  /**
   * 加载 初始化 指派协作 单位
   */
  async loadInitSaveTopicTreeLinkageOrganization() {
    try {
      const response = await initSaveTopicTreeLinkageOrganization();
      if (response.code === 0) {
        this.setData({
          initSaveTreeLinkageOrganizations: this.readyTreeData(response.data),
          isLoadLinkageOrganizations: false
        })

      }
    } catch (error) { }
  },

  /**
   * 点击事件
   * ===========================================================================================================================================================
   */
  //打开选择行业的抽屉
  onClickIndustryDrawer() {
    this.setData({
      viewDrawerIndustryVisible: true,
    });
  },
  //点击选择行业
  onClickIndustryItem(e) {
    //找到value对应的label
    const selectedLabels = e.detail.value.map(id => {
      const industry = this.data.showIndustryList.find(item => item.value === id);
      return industry ? industry.label : '';
    }).join(',');
    this.setData({
      selectedIndustryIds: e.detail.value,
      showIndustryName: selectedLabels
    })
  },
  //打开指派征集单位选择器
  onClickAssignOrganizationDrawer() {
    this.setData({
      viewDrawerAssignVisible: true
    })
    wx.showLoading({
      title: "加载中"
    })
    if (!this.data.isLoadAssignOrganizations) {
      this.setData({
        initSaveTreeAssignOrganizations: this.readyTreeData2(this.data.initSaveTreeAssignOrganizations, this.data.treeAssignOrganizationIds.map((item) => item))
      })
      wx.hideLoading()
    }
  },
  //打开协助媒体选择器
  onClickLinkageOrganizationDrawer() {
    this.setData({
      viewDrawerLinkageVisible: true
    })
    wx.showLoading({
      title: "加载中"
    })
    if (!this.data.isLoadLinkageOrganizations) {
      this.setData({
        initSaveTreeLinkageOrganizations: this.readyTreeData2(this.data.initSaveTreeLinkageOrganizations, this.data.treeLinkageOrganizationIds.map((item) => item))
      })
      wx.hideLoading()
    }
  },
  /**
   * Tree View 指派 征集 单位 点击事件
   * @param e 
   */
  onClickTreeViewAssignItem(e) {
    const { names, idList, item } = e.detail;
    const nameString = names.join('/').substring(0, 10);
    this.setData({
      treeAssignOrganizationIds: idList,
      showOrganizations: nameString
    })
  },

  /**
  * Tree View 指派 协作 单位 点击事件
  * @param e 
  */
  onClickTreeViewLinkaItem(e) {
    const { names, idList } = e.detail;
    const nameString = names.join('/').substring(0, 10);
    this.setData({
      treeLinkageOrganizationIds: idList,
      showLinkageOrganizations: nameString
    })
  },
  // //选择指派征集单位
  // assignOrganizationCascadeChange(res: { detail: any; }) {
  //   const { selectedOptions } = res.detail;
  //   const ids = selectedOptions.map((item) => item.value)
  //   let select = selectedOptions.map((item) => item.label).join('/')
  //   if (select.length > 10 && select.length !== 0) {
  //     select = select.slice(0, 10) + "..."
  //   }
  //   this.setData({
  //     treeAssignOrganizationIds: ids,
  //     showOrganizations: select
  //   });
  // },
  //输入协作描述
  onHelpContentInput(e) {
    this.setData({
      helpContent: e.detail.value
    })
  },
  //输入申报描述
  onRecordDescribesInput(e) {
    this.setData({
      recordDescribes: e.detail.value
    })
  },
  /**
   * 点击选则框的确定按钮回调函数(指派征集单位)
   */
  selectAssignOrganizationListener(e) {
    // //获取数据源
    var allData = e.detail;
    // //获取所有子节点的选项内容(不包括父节点)
    const selectListIds = allData.map((item) => item.id)
    const selectListNames = allData.map((item) => item.lable).join('')
    this.setData({
      treeAssignOrganizationIds: selectListIds,
      showOrganizations: selectListNames.length !== 0 ? selectListNames.slice(0, 10) + "..." : selectListNames.slice(0, 10)
    })
  },

  /**
  * 点击选则框的确定按钮回调函数(协助媒体)
  */
  selectLinkageOrganizationListener(e) {
    // //获取数据源
    var allData = e.detail;
    // //获取所有子节点的选项内容(不包括父节点)
    // let leafNodes = this.allSelectleafNode(allData);
    const selectListIds = allData.map((item) => item.id)
    const selectListNames = allData.map((item) => item.lable).join('')
    this.setData({
      treeLinkageOrganizationIds: selectListIds,
      showLinkageOrganizations: selectListNames.length !== 0 ? selectListNames.slice(0, 10) + "..." : selectListNames.slice(0, 10)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: { topicId: any; mode: any }) {
    this.loadCuesIndustryData();
    this.loadInitSaveTopicTreeLinkageOrganization();
    this.loadInitSaveTopicTreeAssignOrganization();
    if (options.topicId != null) {
      this.setData({ topicId: options.topicId })
      this.getTopicDetails(this.data.topicId)
    }
    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      currentUser,
      showGrade: access.cuesTopicConfigManage,
      mode: options.mode
    })

  },
  //线索征集提交
  async handleSubmit() {
    if (this.data.access.cuesTopicConfigManage && (this.data.grade === '' || this.data.grade === null || this.data.grade === undefined)) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择分类',
      });
      return false
    }
    if (this.data.name === '') {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请输入标题',
      });
      return false
    }
    if (this.data.showIndustryName === '') {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择行业',
      });
      return false
    }
    if (this.data.labelsList.length == 0) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请输入至少一个标签',
      });
      return false
    }
    if (this.data.planContent === '' || this.data.planContent === undefined) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请输入计划描述',
      });
      return false
    }
    if (this.data.datetime === null) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择截止时间',
      });
      return false
    }
    if (this.data.topicId === '') {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '提交中',
        direction: 'column',
        duration: 3000,
        preventScrollThrough: true,
        theme: 'loading',
      });
      getApp().preventActive(async () => {
        const response = await saveCuesTopic({
          assignOrganizationIds: this.data.treeAssignOrganizationIds,
          content: this.data.planContent,
          deadlineTime: this.data.datetime,
          labels: this.data.labelsList,
          linkageDescribes: this.data.helpContent,
          linkageOrganizationIds: this.data.treeLinkageOrganizationIds,
          name: this.data.name,
          industryIds: this.data.selectedIndustryIds,
          createdSource: 2,
          grade: this.data.grade,
          recordDescribes: this.data.recordDescribes
        });
        if (response.code === 0) {

          Message.success({
            context: this,
            offset: [20, 32],
            duration: 5000,
            content: '创建成功',
          });
          this.setData({
            topicId: response.data
          })
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/cues/topic/index?mode=' + this.data.mode
            })// 回到上一个界面
          }, 1000)
          // this.showDialog()
          return true;
        } else {
          Message.error({
            context: this,
            offset: [20, 32],
            duration: 5000,
            content: '创建失败',
          });
          wx.navigateBack();
          return false;
        }
      })
    } else {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '提交中',
        direction: 'column',
        duration: 3000,
        preventScrollThrough: true,
        theme: 'loading',
      });
      let params = {
        id: this.data.topicId,
        assignOrganizationIds: this.data.treeAssignOrganizationIds,
        content: this.data.planContent,
        deadlineTime: this.data.datetime,
        labels: this.data.labelsList,
        linkageDescribes: this.data.helpContent,
        linkageOrganizationIds: this.data.treeLinkageOrganizationIds,
        name: this.data.name,
        industryIds: this.data.selectedIndustryIds,
        recordState: 3,
        createdSource: 2,
        grade: this.data.grade
      }
      getApp().preventActive(async () => {
        const response = await updateTopicManageRecordState(params);
        if (response.code === 0) {
          wx.hideLoading()
          Message.success({
            context: this,
            offset: [20, 32],
            duration: 5000,
            content: '修改成功',
          });
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })// 回到上一个界面
          }, 1000)
          return true;
        } else {
          return false;
        }
      })
    }
  },
  //确认全局通知
  async DialogConfirm() {
    const pushResponse = await sendCuesTopicSendTemplateMessage({
      id: this.data.topicId,
    });
    if (pushResponse.code == 0) {
      Message.success({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '推送成功',
      });
    }
    this.closeDialog()
  },
  //取消全局通知
  DialogCancel() {
    this.closeDialog()
  },
  //显示是否全局通知提示框
  showDialog() {
    this.setData({ showConfirm: true });
  },
  //隐藏是否全局通知提示框
  closeDialog() {
    this.setData({ showConfirm: false });
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      })// 回到上一个界面
    }, 1000)
  },
})